package com.ruoyi.business.service.impl;

import java.math.BigDecimal;
import java.util.*;


import com.ruoyi.business.dao.InventoryDtoDao;
import com.ruoyi.business.domain.DispatchList;
import com.ruoyi.business.dto.InventoryDto;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import org.apache.commons.lang3.StringUtils;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.business.dao.InventoryDao;
import com.ruoyi.business.domain.Inventory;
import com.ruoyi.business.service.IInventoryService;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 * InventoryService业务层处理
 *
 * @author liutietou
 * @since 1.0 2025-06-22
 */
@Transactional(readOnly = true)
@Service
public class InventoryServiceImpl implements IInventoryService {

    @Autowired
    private InventoryDao inventoryDao;
    @Autowired
    private InventoryDtoDao inventoryDtoDao;

    @Autowired
    private TokenService tokenService;

    /**
     * 查询Inventory
     *
     * @param cinvcode InventoryID
     * @return Inventory
     */
    @Override
    public Inventory findById(String cinvcode) {
        return inventoryDao.findById(cinvcode).get();
    }
      @PersistenceContext
       private EntityManager entityManager;
    /**
     * 分页查询Inventory列表
     *
     * @param req Inventory
     * @return Inventory
     */
    @Override
    public Page<InventoryDto> findInventoryPage(InventoryDto req) {
       Specification<InventoryDto> example = formatQueryParams(req);
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Pageable pageable = PageRequest.of(pageDomain.getPageNo(),
                Optional.ofNullable(pageDomain.getPageSize()).orElse(PageDomain.DEFAULT_PAGE_SIZE),
                Sort.Direction.ASC,
                Optional.ofNullable(pageDomain.getOrderByColumn()).orElse("cinvcode"));
        Page<InventoryDto> page = inventoryDtoDao.findAll(example, pageable);
        BigDecimal rate=inventoryDao.getCustomerRate(tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
        page.getContent().forEach(obj->{
            obj.setRate(rate);
        });
        return page;
    }



    public  Specification<InventoryDto> formatQueryParams(InventoryDto req) {
        // 构建基础查询
        Specification<InventoryDto> example = new Specification<InventoryDto>() {
            private static final long serialVersionUID = 1L;
           @Override
            public Predicate toPredicate(Root<InventoryDto> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if (StringUtils.isNotBlank(req.getCinvccode())) {
                    Predicate pre = cb.like(root.get("cinvccode").as(String.class), "%" + req.getCinvccode() + "%");
                    list.add(pre);
                }

                if (StringUtils.isNotBlank(req.getCinvcode())) {
                    Predicate pre = cb.equal(root.get("cinvcode").as(String.class), req.getCinvcode());
                    list.add(pre);
                }

                if (StringUtils.isNotBlank(req.getCinvname())) {
                    Predicate pre = cb.like(root.get("cinvname").as(String.class), "%" + req.getCinvname() + "%");
                    list.add(pre);
                }

                if (req.getNum() != null && StringUtils.isNotBlank(req.getSearchValue())) {
                    if (req.getSearchValue().equals(">")) {
                        Predicate pre = cb.greaterThan(root.get("num").as(BigDecimal.class), req.getNum());
                        list.add(pre);
                    } else if (req.getSearchValue().equals(">=")) {
                        Predicate pre = cb.greaterThanOrEqualTo(root.get("num").as(BigDecimal.class), req.getNum());
                        list.add(pre);
                    } else if (req.getSearchValue().equals("=")) {
                        Predicate pre = cb.equal(root.get("num").as(BigDecimal.class), req.getNum());
                        list.add(pre);
                    } else if (req.getSearchValue().equals("<=")) {
                        Predicate pre = cb.lessThanOrEqualTo(root.get("num").as(BigDecimal.class), req.getNum());
                        list.add(pre);
                    } else if (req.getSearchValue().equals("<")) {
                        Predicate pre = cb.lessThan(root.get("num").as(BigDecimal.class), req.getNum());
                        list.add(pre);
                    }
                }
                if (list.isEmpty()) {
                    return null;
                }
                return cb.and(list.toArray(new Predicate[0]));
            }
        };
       return example;
    }



    /**
     * 分页查询Inventory列表
     *
     * @param req Inventory
     * @return Inventory
     */
    @Override
    public List<Inventory> findInventoryList(Inventory req) {
        Specification<Inventory> example = formatQueryParams(req);
        List<Inventory> list = inventoryDao.findAll(example, Sort.by(Sort.Direction.DESC,"createTime"));
        return list;
    }

    private Specification<Inventory> formatQueryParams(Inventory req){
        Specification<Inventory> example = new Specification<Inventory>() {
            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root<Inventory> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if (StringUtils.isNotBlank(req.getCinvcode())){
                    Predicate pre = cb.equal(root.get("cinvcode").as(String.class), req.getCinvcode());
                    list.add(pre);
                }

                if (StringUtils.isNotBlank(req.getCinvname())){
                    Predicate pre = cb.like(root.get("cinvname").as(String.class), "%" + req.getCinvname()+ "%");
                    list.add(pre);
                }
                if (StringUtils.isNotBlank(req.getCinvstd())){
                    Predicate pre = cb.like(root.get("cinvstd").as(String.class),"%"+ req.getCinvstd()+"%");
                    list.add(pre);
                }
                if (StringUtils.isNotBlank(req.getCinvccode())){
                    Predicate pre = cb.like(root.get("cinvccode").as(String.class), req.getCinvccode() + "%");
                    list.add(pre);
                }

                if (list.isEmpty()) {
                    return null;
                }
                return cb.and(list.toArray(new Predicate[0]));
            }
        };
        return example;
    }

    /**
     * 保存（新增/修改）Inventory
     *
     * @param inventory Inventory
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(Inventory inventory) {
        inventoryDao.save(inventory);
    }


    /**
     * 批量删除Inventory
     *
     * @param cinvcodes 需要删除的InventoryID
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByIds(List<String> cinvcodes) {
        List<Inventory> existBeans = inventoryDao.findAllById(cinvcodes);
        if(!existBeans.isEmpty()){
            inventoryDao.deleteAll(existBeans);
        }
    }

    /**
     * 删除Inventory信息
     *
     * @param cinvcode InventoryID
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteInventoryById(String cinvcode) {
         inventoryDao.deleteById(cinvcode);
    }
}
